package com.ruiyin.controller;

import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Map;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ruiyin.util.MessageUtil;
import com.ruiyin.util.TextMessage;

public class WeixinServlet extends HttpServlet
{
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
  {
	  try
	    {
	      req.setCharacterEncoding("UTF-8");
	      resp.setCharacterEncoding("UTF-8");
	    } catch (UnsupportedEncodingException e1) {
	      e1.printStackTrace();
	    }
	    Map map = MessageUtil.xmlToMap(req);
	    String ToUserName = (String)map.get("ToUserName");
	    String FromUserName = (String)map.get("FromUserName");
	    String MsgType = (String)map.get("MsgType");
	    String Content = (String)map.get("Content");
	    String fromUserName = (String)map.get("MsgId");
	    String message = null;
	    PrintWriter out = null;
	    try {
	      out = resp.getWriter();
	    }
	    catch (IOException e) {
	      e.printStackTrace();
	    }
	    if ("text".equals(MsgType)) {
	      TextMessage text = new TextMessage();
	      text.setFromUserName(ToUserName);
	      text.setToUserName(FromUserName);
	      text.setMsgType("text");
	      //message = MessageUtil.textMessagetoXml(text);
	      text.setCreateTime(new Date().toString());
	      text.setContent("你发送的消息是:" + Content);
	    }
	    System.out.println(message);
	    out.print(message);
	    out.close();
  }

  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
  {
    try
    {
      req.setCharacterEncoding("UTF-8");
      resp.setCharacterEncoding("UTF-8");
    } catch (UnsupportedEncodingException e1) {
      e1.printStackTrace();
    }
    Map map = MessageUtil.xmlToMap(req);
    String ToUserName = (String)map.get("ToUserName");
    String FromUserName = (String)map.get("FromUserName");
    String MsgType = (String)map.get("MsgType");
    String Content = (String)map.get("Content");
    String fromUserName = (String)map.get("MsgId");
    String message = null;
    PrintWriter out = null;
    try {
      out = resp.getWriter();
    }
    catch (IOException e) {
      e.printStackTrace();
    }
    if ("text".equals(MsgType)) {
      TextMessage text = new TextMessage();
      text.setFromUserName(ToUserName);
      text.setToUserName(FromUserName);
      text.setMsgType("text");
      //message = MessageUtil.textMessagetoXml(text);
      text.setCreateTime(new Date().toString());
      text.setContent("你发送的消息是:" + Content);
    }
    System.out.println(message);
    out.print(message);
    out.close();
  }
}
